package com.bruce.ai.alibaba.nacos.prompt.controller;

import org.springframework.web.bind.annotation.RestController;

import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplate;
import com.alibaba.cloud.ai.prompt.ConfigurablePromptTemplateFactory;

import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;
import org.slf4j.Logger;



import java.util.Map;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 测试动态 prompt 模板
 */
@RequestMapping("/prompt")
@RestController
public class PromptController {

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(PromptController.class);

    private final ChatClient client;

    private final ConfigurablePromptTemplateFactory promptTemplateFactory;

    public PromptController(
            ChatModel chatModel,
            ConfigurablePromptTemplateFactory promptTemplateFactory
    ) {

        this.client = ChatClient.builder(chatModel).build();
        this.promptTemplateFactory = promptTemplateFactory;
    }

    @GetMapping("/instruduce")
    public Flux<String> instruduce(
            @RequestParam(value = "personName", required = false, defaultValue = "周杰伦") String personName,
            HttpServletResponse response
    ) {

        // 防止输出乱码
        response.setCharacterEncoding("UTF-8");

        // 使用 nacos 的 prompt tmpl 创建 prompt
        ConfigurablePromptTemplate template = promptTemplateFactory.create(
                "instruduce",  // 对应提示模板中的name
                "请简单介绍一下周杰伦，100字以内."
        );
        Prompt prompt = template.create(Map.of("personName", personName));
        logger.info("最终构建的 prompt 为：{}", prompt.getContents());

        return client.prompt(prompt)
                .stream()
                .content();
    }
}
